<template>
  <div class="app-container">
    <!-- 模式标识 -->
    <el-tag :type="modeTagType" effect="dark" class="mode-tag">
      {{ modeText }}
    </el-tag>
    <!-- 导航选项卡 -->
    <el-tabs v-model="activeTab" type="card" class="course-tabs">
      <!-- 第一页：基本信息 -->
      <el-tab-pane label="基本信息" name="basic">
        <div class="form-container">
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="课程编号" prop="courseCode">
            <el-input v-model="form.courseCode" placeholder="请输入课程编号"       :disabled="isViewMode"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="课程名称" prop="courseName">
            <el-input v-model="form.courseName" placeholder="请输入课程名称"       :disabled="isViewMode"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="课程英文名称" prop="courseNameEn">
            <el-input v-model="form.courseNameEn" placeholder="请输入课程英文名称"  :disabled="isViewMode"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="课程简称" prop="courseShortName">
            <el-input v-model="form.courseShortName" placeholder="请输入课程简称"  :disabled="isViewMode"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="学分" prop="credits">
            <el-input-number v-model="form.credits" :min="0.5" :max="10" :step="0.5" style="width:100%" :disabled="isViewMode"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总学时" prop="totalHours">
            <el-input-number v-model="form.totalHours" :min="1" :max="200" style="width:100%" :disabled="isViewMode"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开课状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择开课状态" style="width:100%"      :disabled="isViewMode">
              <el-option
                  v-for="dict in statusOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                  :disabled="isViewMode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开课学院" prop="collegeId">
            <el-select
                v-model="form.collegeId"
                placeholder="请选择开课学院"
                style="width:100%"
                :disabled="isViewMode"
                clearable
                filterable
            >
              <el-option
                  v-for="item in collegeList"
                  :key="item.collegeId"
                  :label="item.collegeName"
                  :value="item.collegeCode"
              />
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开课学期" prop="semester">
            <el-select v-model="form.semester" placeholder="请选择开课学期" style="width:100%"      :disabled="isViewMode">
              <el-option
                  v-for="dict in semesterOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                  :disabled="isViewMode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="课程性质" prop="courseNature">
            <el-select v-model="form.courseNature" placeholder="请选择课程性质" style="width:100%"      :disabled="isViewMode">
              <el-option
                  v-for="dict in courseNatureOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                  :disabled="isViewMode"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="是否跨学期" prop="isCrossSemester">
            <el-select
                v-model="form.isCrossSemester"
                placeholder="是否跨学期"
                style="width:100%"
                :disabled="isViewMode"
            >
              <el-option
                  v-for="dict in isCrossSemesterOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                  :disabled="isViewMode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="跨学期时长" prop="crossSemesterCount">
            <el-select
                v-model="form.crossSemesterCount"
                placeholder="请选择跨学期时长"
                style="width:100%"
                :disabled="isViewMode || !isCrossSemesterSelected"
            >
              <el-option
                  v-for="dict in crossSemesterCountOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                  :disabled="isViewMode"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="考核方式" prop="examinationMethod">
            <el-select v-model="form.examinationMethod" placeholder="请选择考核方式" style="width:100%"      :disabled="isViewMode">
              <el-option
                  v-for="dict in examinationMethodOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                  :disabled="isViewMode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="成绩类型" prop="gradeType">
            <el-select v-model="form.gradeType" placeholder="请选择成绩类型" style="width:100%"      :disabled="isViewMode">
              <el-option
                  v-for="dict in gradeTypeOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                  :disabled="isViewMode"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="课程类型" prop="courseType">
            <el-select v-model="form.courseType" placeholder="请选择课程类型" style="width:100%"      :disabled="isViewMode">
              <el-option
                  v-for="dict in courseTypeOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                  :disabled="isViewMode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="教学方式" prop="teachingMethod">
            <el-select v-model="form.teachingMethod" placeholder="请选择教学方式" style="width:100%"      :disabled="isViewMode">
              <el-option
                  v-for="dict in teachingMethodOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                  :disabled="isViewMode"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">

        <el-col :span="12">
          <el-form-item label="适用学院" prop="applicableDepartments">
            <el-select
                v-model="form.applicableDepartments"
                placeholder="请选择适用学院"
                style="width:100%"
                :disabled="isViewMode"
                @change="handleApplicableCollegeChange"
                clearable
                filterable
            >
              <el-option
                  v-for="item in collegeList"
                  :key="item.collegeId"
                  :label="item.collegeName"
                  :value="item.collegeCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="适用专业" prop="applicableMajors">
            <el-select
                v-model="form.applicableMajors"
                multiple
                placeholder="请选择适用专业"
                style="width:100%"
                :disabled="isViewMode || !form.applicableDepartments"
                filterable
            >
              <el-option
                  v-for="item in majorList"
                  :key="item.majorId"
                  :label="item.majorName"
                  :value="item.majorCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="实验/实践学时" prop="labHours">
            <el-input-number v-model="form.labHours" :min="0" :max="100" :step="1" style="width:100%" :disabled="isViewMode"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="自学学时" prop="selfStudyHours">
            <el-input-number v-model="form.selfStudyHours" :min="0" :max="100" :step="1" style="width:100%" :disabled="isViewMode"/>
          </el-form-item>
        </el-col>
      </el-row>



      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="教室类型" prop="classroomType">
            <el-select v-model="form.classroomType" placeholder="请选择教室类型" style="width:100%"      :disabled="isViewMode">
              <el-option
                  v-for="dict in classroomTypeOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                  :disabled="isViewMode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="授课语言" prop="teachingLanguage">
            <el-select v-model="form.teachingLanguage" placeholder="请选择授课语言" style="width:100%"      :disabled="isViewMode">
              <el-option
                  v-for="dict in teachingLanguageOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                  :disabled="isViewMode"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>


    </el-form>
        </div>
      </el-tab-pane>


      <!-- 第二页：先修课程 -->
      <el-tab-pane label="先修课程" name="prerequisite">
        <div class="form-container"  style="display: flex;margin-top: 30px; justify-content: center;">
      <el-form-item label="先修课程" prop="prerequisiteCourses" style="width: 100%; max-width: 1800px;">
        <el-input
            v-model="form.prerequisiteCourses"
            type="textarea"
            :rows="15"
            placeholder="请输入先修课程要求"
            :disabled="isViewMode"
        />
      </el-form-item>
        </div>
      </el-tab-pane>

      <!-- 第三页：课程简介 -->
      <el-tab-pane label="课程简介" name="introduction">
        <div class="form-container" style="display: flex;margin-top: 30px; justify-content: center;">
      <el-form-item label="课程简介" prop="courseIntroduction" style="width: 100%; max-width: 1800px;">
        <el-input
            v-model="form.courseIntroduction"
            type="textarea"
            :rows="15"
            placeholder="请输入课程简介"
            :disabled="isViewMode"
        />
      </el-form-item>
        </div>
      </el-tab-pane>

          <el-tab-pane label="参考书目" name="referencebook">
            <div class="form-container" style="display: flex;margin-top: 30px; justify-content: center;">
      <el-form-item label="参考书目" prop="referenceBooks"   style="width: 100%; max-width: 1800px;">
        <el-input
            v-model="form.referenceBooks"
            type="textarea"
            :rows="15"
            placeholder="请输入参考书目"
            :disabled="isViewMode"
        />
      </el-form-item>
            </div>
          </el-tab-pane>

      <!-- 第五页：教学进度安排 -->
      <el-tab-pane label="教学进度安排" name="teachingarrangement">
        <div class="form-container" style="display: flex;margin-top: 30px; justify-content: center;">
          <el-form-item label="教学进度安排"
                        prop="teachingArrangement"
                        style="width: 100%; max-width: 1800px;"
          >
            <el-input
                v-model="form.teachingArrangement"
                type="textarea"
                :rows="15"
                placeholder="请输入教学进度安排"
                :disabled="isViewMode"
            />
          </el-form-item>
        </div>
      </el-tab-pane>
      <!-- 第六页：课程大纲 -->
      <el-tab-pane label="课程大纲" name="courseoutline">
        <div class="form-container" style="display: flex;margin-top: 30px; justify-content: center;">
          <el-form-item
              label="课程大纲"
              prop="courseOutline"
              style="width: 100%; max-width: 1800px;"
          >
          <el-input
              v-model="form.courseOutline"
              type="textarea"
              :rows="15"
          placeholder="请输入课程大纲"
          :disabled="isViewMode"
          />
          </el-form-item>
        </div>
      </el-tab-pane>

    </el-tabs>
      <!-- 其他表单行保持不变，只需在el-select上添加:disabled="isViewMode" -->

    <div class="action-buttons" style="margin-top: 40px; display: flex; justify-content: center;">
        <!-- 返回按钮永远不禁用 -->
        <!-- 明确设置 disabled=false -->
        <el-button @click="goBack" :disabled="false"    style="width: 80%; max-width: 100px;">返回</el-button>
        <!-- 保存/创建按钮在查看模式下隐藏 -->
        <el-button
            v-if="!isViewMode"
            type="primary"
            @click="submitForm"
            style="width: 80%; max-width: 100px; margin-left:40px "
        >
          {{ isCreateMode ? '创建' : '保存' }}
        </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getCourse, addCourse, updateCourse } from '@/api/course/course'
import { listCollege } from '@/api/college/college'
import { listMajor, getMajorByCollegeId } from "@/api/major/major";
const activeTab = ref('basic')
const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const collegeList = ref([]);
const majorList = ref([]);
const zyZlist = ref([]); // 所有专业列表，用于显示名称
// 模式计算属性
const isCreateMode = computed(() => !route.params.id)
const isEditMode = computed(() => route.query.mode === 'edit')
const isViewMode = computed(() => !isCreateMode.value && !isEditMode.value)

const modeText = computed(() => {
  return isCreateMode.value ? '新增课程'
      : isEditMode.value ? '修改课程'
          : '查看课程详情'
})

const modeTagType = computed(() => {
  return isCreateMode.value ? 'success'
      : isEditMode.value ? 'warning'
          : 'info'
})

// 表单数据
const form = ref({
  id: null,
  courseCode: '',
  courseName: '',
  courseNameEn: '',
  courseShortName: '',
  collegeId: null,
  applicableDepartments: null,
  credits: 0,
  totalHours: 0,
  semester: '',
  courseNature: '',
  courseLevel: '',
  gradeType: '',
  courseType: '',
  teachingMethod: '',
  prerequisiteCourses: '',
  teachingArrangement: '',
  courseOutline: '',
  courseIntroduction: '',
  teachingLanguage: '',
  referenceBooks: '',
  classroomType: '',
  isCrossSemester: '',
  labHours: 0,
  selfStudyHours: 0,
  crossSemesterCount: '',
  applicableMajors: [],
  status: 1
})

// 表单验证规则
const rules = {
  courseCode: [{ required: true, message: "课程编号不能为空", trigger: "blur" }],
  courseName: [{ required: true, message: "课程名称不能为空", trigger: "blur" }],
  collegeId: [{ required: true, message: "请选择开课学院", trigger: "change" }],
  credits: [{ required: true, message: "请输入学分", trigger: "blur" }],
  totalHours: [{ required: true, message: "请输入总学时", trigger: "blur" }],
  semester: [{ required: true, message: "请选择开课学期", trigger: "change" }],
  courseNature: [{ required: true, message: "请选择课程性质", trigger: "change" }],
  status: [{ required: true, message: "请选择开课状态", trigger: "change" }]
}

// 字典数据
const {
  characteristics_of_the_course,
  type_of_course,
  semester: semesterDict,
  course_status,
  examination_method,
  grade_type,
  teaching_method,
  teaching_language,
  classroom_type,
  crosssemester_count,
  iscross_semester,
  sys_major
} = proxy.useDict(
    'characteristics_of_the_course',
    'type_of_course',
    'semester',
    'course_status',
    'examination_method',
    'grade_type',
    'teaching_method',
    'teaching_language',
    'classroom_type',
    'crosssemester_count',
    'iscross_semester',
    'sys_major'
)

const collegeOptions = ref([])
const semesterOptions = semesterDict
const courseNatureOptions = characteristics_of_the_course
const examinationMethodOptions = examination_method
const gradeTypeOptions = grade_type
const courseTypeOptions = type_of_course
const teachingMethodOptions = teaching_method
const teachingLanguageOptions = teaching_language
const classroomTypeOptions = classroom_type
const crossSemesterCountOptions = crosssemester_count
const isCrossSemesterOptions = iscross_semester
const statusOptions = course_status
const majorOptions = sys_major
/** 学院变化处理函数 */
async function handleApplicableCollegeChange(collegeCode) {
  console.log('选中的院校代码:', collegeCode);

  if (!collegeCode) {
    majorList.value = [];
    form.value.applicableMajors = [];
    return;
  }

  try {
    const response = await getMajorByCollegeId(collegeCode);
    majorList.value = response.rows;

    // 确保专业列表加载完成后再设置选中值
    if (form.value.applicableMajors?.length) {
      // 保持当前选中的专业（如果有）
      form.value.applicableMajors = form.value.applicableMajors.filter(majorCode =>
          majorList.value.some(m => m.majorCode === majorCode))
    }
  } catch (error) {
    console.error('获取专业列表失败:', error);
    majorList.value = [];
  }
}
/** 获取学院列表信息 */
function getCollegeList() {
  listCollege({}).then(response => {
    collegeList.value = response.rows;
  }).catch(error => {
    console.error('加载学院列表失败:', error);
    proxy.$modal.msgError('加载学院列表失败');
  });
}
/** 获取所有专业列表 */
function getlistMajor() {
  listMajor({}).then(response => {
    zyZlist.value = response.rows;
  }).catch(error => {
    console.error('加载专业列表失败:', error);
    proxy.$modal.msgError('加载专业列表失败');
  });
}


// 加载课程数据
const loadCourseData = async () => {
  try {
    const res = await getCourse(route.params.id)
    form.value = res.data

    // 处理适用专业数据（确保是数组格式）
    form.value.applicableMajors = typeof form.value.applicableMajors === 'string'
        ? form.value.applicableMajors.split(',').filter(Boolean).map(code => code.trim())
        : form.value.applicableMajors || []

    // 如果有适用学院，需要加载该学院的专业列表以便正确显示专业名称
    if (form.value.applicableDepartments) {
      await handleApplicableCollegeChange(form.value.applicableDepartments)
    }

    console.log('加载的适用专业:', form.value.applicableMajors)
  } catch (error) {
    console.error('加载课程数据失败:', error)
  }
}
// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    const submitData = {
      ...form.value,
      applicableMajors: Array.isArray(form.value.applicableMajors)
          ? form.value.applicableMajors.join(',')
          : form.value.applicableMajors
    }

    if (isCreateMode.value) {
      await addCourse(submitData)
      proxy.$modal.msgSuccess('新增成功')
    } else {
      await updateCourse(submitData)
      proxy.$modal.msgSuccess('修改成功')
    }

    goBack()
  } catch (error) {
    console.error('表单提交失败:', error)
    if (error !== 'validate') {
      proxy.$modal.msgError('操作失败，请重试')
    }
  }
}

// 添加是否为跨学期课程的计算
const isCrossSemesterSelected = computed(() => {
  return form.value.isCrossSemester === 0 // 0表示"是"
})

// 添加watch监听
watch(() => form.value.isCrossSemester, (newVal) => {
  if (newVal !== 0) { // 如果不是"是"
    form.value.crossSemesterCount = null // 重置为null
  }
})


// 返回列表
const goBack = () => {
  window.close()
  router.go(-1) // 返回上一页
}
// 初始化
onMounted(async () => {
  await getCollegeList()
  if (!isCreateMode.value) {
    await loadCourseData()
  }
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.mode-tag {
  margin-bottom: 20px;
  font-size: 14px;
}
</style>